package TankGame;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

// 游戏面板
class GamePanel extends JPanel implements KeyListener {
    private Tank playerTank;
    private List<Bullet> bullets;
    private List<Obstacle> obstacles;
    private List<EnemyTank> enemyTanks;
    private Timer gameTimer;
    private Timer enemyMovementTimer;
    private TankGame tankGame;
    private boolean isPaused;

    private JButton pauseButton;

    // 定义新的游戏区域大小
    private final int GAME_WIDTH = 800;
    private final int GAME_HEIGHT = 500;

    public GamePanel(TankGame tankGame) {
        this.tankGame = tankGame;
        setBackground(Color.LIGHT_GRAY);
        setPreferredSize(new Dimension(GAME_WIDTH, GAME_HEIGHT));
        setFocusable(true);
        addKeyListener(this);

        playerTank = new Tank(250, 250);
        bullets = new ArrayList<>();
        obstacles = new ArrayList<>();
        enemyTanks = new ArrayList<>();

        // 添加障碍物
        obstacles.add(new Obstacle(0, 150, 300, 25, 3));
        obstacles.add(new Obstacle(400, 300, 25, 200, 3));

        // 添加敌方坦克
        enemyTanks.add(new EnemyTank(50, 50, 100));
        enemyTanks.add(new EnemyTank(550, 400, 100));

        // 为每个敌军坦克设置射击定时器
        for (EnemyTank enemyTank : enemyTanks) {
            Timer shootingTimer = new Timer(2000, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Bullet bullet = enemyTank.shoot();
                    if (bullet != null) {
                        bullets.add(bullet);
                    }
                    // 设置冷却时间
                    Timer cooldownTimer = new Timer(5000, new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            enemyTank.resetShooting();
                        }
                    });
                    cooldownTimer.setRepeats(false);
                    cooldownTimer.start();
                }
            });
            shootingTimer.setRepeats(true);
            shootingTimer.start();
        }

        // 设置定时器，每100毫秒更新一次游戏状态
        gameTimer = new Timer(100, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!isPaused) {
                    updateGame();
                    repaint();
                }
            }
        });

        // 设置敌军坦克移动定时器，每500毫秒更新一次敌军坦克的位置
        enemyMovementTimer = new Timer(500, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!isPaused) {
                    moveEnemies();
                }
            }
        });

        isPaused = false;

        pauseButton = new JButton("暂停");
        pauseButton.setFont(new Font("仿宋体", Font.BOLD, 24));
        pauseButton.setForeground(Color.WHITE);
        pauseButton.setBackground(Color.GRAY);
        pauseButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                togglePause();
            }
        });

        JButton exitButton = new JButton("退出游戏");
        exitButton.setFont(new Font("仿宋体", Font.BOLD, 24));
        exitButton.setForeground(Color.WHITE);
        exitButton.setBackground(Color.GRAY);
        exitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });

        // 使用 BorderLayout 布局管理器
        setLayout(new BorderLayout());

        // 创建按钮面板并将按钮添加进去
        JPanel buttonPanel = new JPanel();
        buttonPanel.setOpaque(false);
        buttonPanel.add(pauseButton);
        buttonPanel.add(exitButton);

        // 将按钮面板放在 BorderLayout 的 SOUTH 区域
        add(buttonPanel, BorderLayout.SOUTH);
    }

    public void startGameLoop() {
        gameTimer.start();
        enemyMovementTimer.start();
    }

    private void updateGame() {
        playerTank.move(obstacles, enemyTanks, GAME_WIDTH, GAME_HEIGHT);
        for (Bullet bullet : bullets) {
            bullet.move();
        }
        checkCollisions();
    }

    private void checkCollisions() {
        // 检查子弹与障碍物的碰撞
        for (int i = bullets.size() - 1; i >= 0; i--) {
            Bullet bullet = bullets.get(i);
            for (int j = obstacles.size() - 1; j >= 0; j--) {
                Obstacle obstacle = obstacles.get(j);
                if (bullet.getBounds().intersects(obstacle.getBounds())) {
                    bullets.remove(bullet);
                    obstacle.hit();
                    if (obstacle.isDestroyed()) {
                        obstacles.remove(obstacle);
                    }
                    break;
                }
            }
        }

        // 检查玩家子弹与敌方坦克的碰撞
        for (int i = bullets.size() - 1; i >= 0; i--) {
            Bullet bullet = bullets.get(i);
            if (bullet.isPlayerBullet()) {
                for (int j = enemyTanks.size() - 1; j >= 0; j--) {
                    EnemyTank enemyTank = enemyTanks.get(j);
                    if (bullet.getBounds().intersects(enemyTank.getBounds())) {
                        bullets.remove(bullet);
                        enemyTank.takeDamage(20);
                        if (enemyTank.isDestroyed()) {
                            enemyTanks.remove(enemyTank);
                            bullets.removeIf(b -> !b.isPlayerBullet());
                        }
                        break;
                    }
                }
            } else {
                if (bullet.getBounds().intersects(playerTank.getBounds())) {
                    bullets.remove(bullet);
                    playerTank.takeDamage(20);
                    if (playerTank.isDestroyed()) {
                        tankGame.gameOver(false);
                    }
                    break;
                }
            }
        }

        // 检查子弹是否超出游戏区域
        for (int i = bullets.size() - 1; i >= 0; i--) {
            Bullet bullet = bullets.get(i);
            if (bullet.getX() < 0 || bullet.getX() > GAME_WIDTH ||
                    bullet.getY() < 0 || bullet.getY() > GAME_HEIGHT) {
                bullets.remove(bullet);
            }
        }

        // 检查敌方坦克是否被全部消灭
        if (enemyTanks.isEmpty()) {
            tankGame.gameOver(true);
        }
    }

    private void moveEnemies() {
        for (EnemyTank enemyTank : enemyTanks) {
            changeEnemyDirectionRandomly(enemyTank);
            moveEnemy(enemyTank);
        }
    }

    private void changeEnemyDirectionRandomly(EnemyTank enemyTank) {
        Random random = new Random();
        enemyTank.setDirection(EnemyTank.Direction.values()[random.nextInt(EnemyTank.Direction.values().length)]);
    }

    private void moveEnemy(EnemyTank enemyTank) {
        int newX = enemyTank.getX();
        int newY = enemyTank.getY();

        switch (enemyTank.getDirection()) {
            case UP:
                if (newY > 0) newY -= enemyTank.speed;
                break;
            case DOWN:
                if (newY < GAME_HEIGHT - 50) newY += enemyTank.speed;
                break;
            case LEFT:
                if (newX > 0) newX -= enemyTank.speed;
                break;
            case RIGHT:
                if (newX < GAME_WIDTH - 50) newX += enemyTank.speed;
                break;
        }

        // 检查新位置是否与任何障碍物相交
        boolean canMove = true;
        for (Obstacle obstacle : obstacles) {
            if (new Rectangle(newX, newY, 50, 50).intersects(obstacle.getBounds())) {
                canMove = false;
                break;
            }
        }

        // 检查新位置是否与玩家坦克相交
        if (new Rectangle(newX, newY, 50, 50).intersects(playerTank.getBounds())) {
            canMove = false;
        }

        // 检查新位置是否超出游戏边界
        if (newX < 0 || newX > GAME_WIDTH - 60 || newY < 0 || newY > GAME_HEIGHT - 50) {
            canMove = false;
        }

        if (canMove) {
            enemyTank.x = newX;
            enemyTank.y = newY;
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;

        // 设置背景颜色
        setBackground(Color.DARK_GRAY);

        playerTank.draw(g2d);
        for (Bullet bullet : bullets) {
            bullet.draw(g2d);
        }
        for (Obstacle obstacle : obstacles) {
            obstacle.draw(g2d);
        }

        // 绘制所有敌方坦克
        for (EnemyTank enemyTank : enemyTanks) {
            enemyTank.draw(g2d);
        }

        // 绘制双横线
        g2d.setStroke(new BasicStroke(3, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[]{9}, 0));
        g2d.setColor(Color.GRAY);
        g2d.drawLine(0, GAME_HEIGHT, GAME_WIDTH, GAME_HEIGHT);
        g2d.drawLine(0, GAME_HEIGHT + 3, GAME_WIDTH, GAME_HEIGHT + 3);
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if (!isPaused) {
            playerTank.keyPressed(e);
            if (e.getKeyCode() == KeyEvent.VK_SPACE) {
                bullets.add(playerTank.shoot());
            }
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        if (!isPaused) {
            playerTank.keyReleased(e);
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    private void togglePause() {
        isPaused = !isPaused;
        if (isPaused) {
            gameTimer.stop();
            enemyMovementTimer.stop();
            JOptionPane.showMessageDialog(this, "游戏已暂停", "暂停", JOptionPane.INFORMATION_MESSAGE);
        } else {
            gameTimer.start();
            enemyMovementTimer.start();
            JOptionPane.showMessageDialog(this, "游戏已继续", "继续", JOptionPane.INFORMATION_MESSAGE);
            requestFocusInWindow();
        }
        String buttonText = isPaused ? "继续" : "暂停";
        pauseButton.setText(buttonText);
    }
}